package com.zzmm.socket.qq.server;

import cn.hutool.core.util.ObjectUtil;
import com.zzmm.socket.qq.common.ConsoleUtil;
import com.zzmm.socket.qq.common.DataBase;
import com.zzmm.socket.qq.common.Message;
import com.zzmm.socket.qq.common.QQConstant;
import lombok.SneakyThrows;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;

import static com.zzmm.socket.qq.common.QQConstant.MessageType.SERVER_PUSH;
import static com.zzmm.socket.qq.common.QQConstant.SERVER_PORT;

public class QQServer {

    public static void main(String[] args) {
        new QQServer().service();
    }

    private final ServerSocket serverSocket;

    @SneakyThrows
    public QQServer() {
        this.serverSocket = new ServerSocket(SERVER_PORT);
        new PushThread().start();
    }

    @SneakyThrows
    public void service() {

        while (!serverSocket.isClosed()) {
            ConsoleUtil.println("服务器正在等待客户端连接...");
            Socket socket = serverSocket.accept();
            ServerSocketManager.add(socket);
        }

    }

    private static final class PushThread extends Thread {

        @Override
        public void run() {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String content = scanner.next();
                if ("exit".equals(content)) {
                    break;
                }

                Message message = Message.builder()
                        .sender("server")
                        .content(content)
                        .messageType(SERVER_PUSH)
                        .build();

                DataBase.listAllUsername()
                        .forEach(username -> {
                            // 设置接收人
                            message.setReceiver(username);

                            ServerSocketManager.UserSocketManager userSocketManager = ServerSocketManager.get(username);
                            if (ObjectUtil.isNull(userSocketManager)) {
                                // 离线存储
                                DataBase.saveOfflineMessageByUsernameIfExists(message);
                            } else {
                                userSocketManager.writeMessage(message);
                            }
                        });
            }
        }
    }


}
